
package com.j2eefast.flowable.bpm.controller;
import com.j2eefast.common.core.business.annotaion.BussinessLog;
import com.j2eefast.common.core.controller.BaseController;
import com.j2eefast.common.core.enums.BusinessType;
import com.j2eefast.common.core.utils.PageUtil;
import com.j2eefast.common.core.utils.ResponseData;
import com.j2eefast.common.core.utils.ToolUtil;
import com.j2eefast.common.core.utils.ValidatorUtil;
import com.j2eefast.flowable.bpm.entity.ProjectArchivesEntity;
import com.j2eefast.flowable.bpm.entity.ProjectClaimEntity;
import com.j2eefast.flowable.bpm.entity.ProjectClaimRecordEntity;
import com.j2eefast.flowable.bpm.entity.ProjectSanLianEntity;
import com.j2eefast.flowable.bpm.service.ArchivesService;
import com.j2eefast.flowable.bpm.service.ClaimService;
import com.j2eefast.flowable.bpm.service.ManagerService;
import com.j2eefast.flowable.bpm.service.SanLianService;
import com.j2eefast.flowable.bpm.utils.StringUtils;
import com.j2eefast.framework.annotation.RepeatSubmit;
import com.j2eefast.framework.sys.entity.SysUserEntity;
import com.j2eefast.framework.sys.service.SysUserService;
import com.j2eefast.framework.utils.UserUtils;
import io.swagger.models.auth.In;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>到账认领管理</p>
 *
 * @author: zhangyuan
 * @date: 2021-04-29 00:02
 * @web: http://www.letukeji.cn
 * @version: 1.0.1
 */
@Controller
@RequestMapping("/bpm/claim")
public class ClaimController extends BaseController {

	private String urlPrefix = "modules/bpm/claim";
	@Autowired
	private ClaimService claimService;
	@Autowired
	private ManagerService managerService;
	@Autowired
	private SanLianService sanLianService;
	@Autowired
	private ArchivesService archivesService;
	@Autowired
	private com.j2eefast.framework.sys.service.SysUserService sysUserService;

	/**
	 * 删除
	 */
	@RepeatSubmit
	@BussinessLog(title = "删除", businessType = BusinessType.DELETE)
	@RequestMapping(value = "/del", method = RequestMethod.POST)
	@RequiresPermissions("bpm:claim:del")
	@ResponseBody
	public ResponseData deleteClaim(HttpServletRequest request) {
		String str = request.getParameter("ids");
		if (str != "") {
			String[] s = str.split(",");
			Long[] ids = (Long[]) ConvertUtils.convert(s,Long.class);
			return claimService.deleteClaim(ids) ? success() : error("删除失败!");
		} else {
			return this.error("删除失败");
		}
	}

	/**
	 * 认领信息列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("bpm:claim:list")
	@ResponseBody
	public ResponseData list(@RequestParam Map<String, Object> params) {
		PageUtil page = claimService.findPage(params);
		return success(page);
	}

	@RequiresPermissions("bpm:claim")
	@GetMapping()
	public String claim() {
		return urlPrefix + "/claim";
	}


	/**
	 * 修改认领 页面
	 */
	@RequiresPermissions("bpm:claim:edit")
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap) {
		ProjectClaimEntity projectClaimEntity = claimService.getByIds(id);
		mmap.put("claimTaskFrom", projectClaimEntity);
		return urlPrefix + "/edit";
	}

	/**
	 * 修改修改认领保存
	 */
	@RepeatSubmit
	@RequiresPermissions("bpm:claim:edit")
	@BussinessLog(title = "认领", businessType = BusinessType.UPDATE)
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData edit(ProjectClaimEntity projectClaimEntity) {
		ValidatorUtil.validateEntity(projectClaimEntity);
		return claimService.updateByIds(projectClaimEntity) ? success() : error("修改失败!");
	}
	/**
	 * 新增参数配置
	 */
	@RequiresPermissions("bpm:claim:add")
	@GetMapping("/add")
	//@RequiresPermissions("bpm:claim:add")
	public String add() {
		return urlPrefix + "/add";
	}

	/**
	 * 新增认领保存
	 */
	@RepeatSubmit
	@RequiresPermissions("bpm:claim:add")
	@BussinessLog(title = "认领", businessType = BusinessType.INSERT)
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData addSave(@Validated ProjectClaimEntity projectClaimEntity) {
		//校验参数
		ValidatorUtil.validateEntity(projectClaimEntity);
		return claimService.save(projectClaimEntity) ? success() : error("新增失败!");
	}

	//到账认领

	/**
	 * 修改认领 页面
	 */
	@RequiresPermissions("bpm:claim:editClaim")
	@GetMapping("/editClaim/{id}")
	public String editClaim(@PathVariable("id") Long id, ModelMap mmap) {
		Long userId = UserUtils.getUserInfo().getId();
		ProjectClaimEntity projectClaimEntity = claimService.getByIds(id);
		mmap.put("claimTaskFrom", projectClaimEntity);
		List<ProjectClaimRecordEntity> recordList = claimService.recordList(userId, id);
		mmap.put("recordList", recordList);
		return urlPrefix + "/editClaim";


	}

	/**
	 * 修改修改认领保存
	 */
	@RepeatSubmit
	@RequiresPermissions("bpm:claim:editClaim")
	@BussinessLog(title = "认领箱", businessType = BusinessType.UPDATE)
	@RequestMapping(value = "/editClaim", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData editClaim(HttpServletRequest request, Model model) throws ParseException {
		Long claimId = Long.parseLong(request.getParameter("claimId"));//认领id
		Long userId = Long.parseLong(request.getParameter("userId"));//用户id
		String total_items = request.getParameter("total_items");//认领插入条数
		ValidatorUtil.validateEntity(total_items);
		int total = Integer.valueOf(total_items);
		//批量删除 先不考虑性能
		claimService.deleteRecord(request);
		//SysUserEntity userEntity = sysUserService.getSysById(Long.parseLong(request.getParameter(nameId)));
		//return claimService.saveRecord(request)?success():error("保存失败!");


		//批量删除 先不考虑性能
//		String str = request.getParameter("itemsToRemove");//删除的行的ID信息
//		List<ProjectClaimRecordEntity> recordEntity = claimService.recordList(userId, claimId);//获取认领金额信息记录
//		if (str != "" && recordEntity != null) {
//			String[] arr = str.split(","); // 用,分割
//			for (int i = 0; i < arr.length; i++) {
//				for (int j = 0; j < recordEntity.size(); j++) {
//					System.out.println(str != "");
//					if (Long.parseLong(arr[i]) == recordEntity.get(j).getId()) {
//						claimService.deleteRecord(recordEntity.get(j).getId());
//					}
//				}
//			}
//		}

//		//获取前端传值
		List<ProjectClaimRecordEntity> recordList = new ArrayList<ProjectClaimRecordEntity>();//更新数据放这里面
		List<ProjectClaimRecordEntity> recordList1 = new ArrayList<ProjectClaimRecordEntity>();//新增数据放这里
		BigDecimal arrivalAmount = StringUtils.StringDecimal(request.getParameter("arrivalAmount"));//总金额
		BigDecimal sum = new BigDecimal("0.00");
		for (int i = 1; i <= total; i++) {
			String id = "id_" + i;
			String nameId = "nameId_" + i;
			String fileId = "fileId_" + i;
			String sanlianId = "sanlianId_" + i;
			String claimType = "claimType_" + i;
			String openDepartment = "openDepartment_" + i;
			String claimTime = "claimTime_" + i;
			String remarks = "remarks_" + i;
			String putAmount = "putAmount_" + i;
			String claimNumber = "claimNumber_" + i;
			Date date = new Date();//创建一个时间对象，获取到当前的时间
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
			ProjectClaimRecordEntity user = new ProjectClaimRecordEntity();
			user.setNameId(Long.parseLong(request.getParameter(nameId)));
			user.setSanlianId(Long.parseLong(request.getParameter(sanlianId)));
			user.setFileId(Long.parseLong(request.getParameter(fileId)));
			user.setClaimType(request.getParameter(claimType));
			user.setClaimTime(simpleDateFormat.parse(request.getParameter(claimTime)));
			user.setOpenDepartment(request.getParameter(openDepartment));
			user.setRemarks(request.getParameter(remarks));
			//user.setClaimNumber(Double.valueOf(request.getParameter(claimNumber)));
			user.setPutAmount(StringUtils.StringDecimal(request.getParameter(putAmount)));
			user.setClaimId(claimId);
			user.setUserId(userId);
			sum = sum.add(user.getPutAmount());
			SysUserEntity userEntity = sysUserService.getSysById(Long.parseLong(request.getParameter(nameId)));
			//	ProjectSanLianEntity sanlianEntity = sanLianService.getSanlianById(Long.parseLong(request.getParameter(sanlianId)));
			ProjectSanLianEntity sanlianEntity = sanLianService.getSanlianId();
			//ProjectArchivesEntity fileEntity = archivesService.getArchivesById(Long.parseLong(request.getParameter(fileId)));
			ProjectArchivesEntity fileEntity = archivesService.getArchivesId();
			if (userEntity != null) {
				user.setCeoName(userEntity.getName());
			}
			if (sanlianEntity != null) {
				user.setSanlianNo(sanlianEntity.getName());
			}
			if (fileEntity != null) {
				user.setFileNumber(fileEntity.getName());
			}
			if (request.getParameter(id) != "") {
				user.setId(Long.parseLong(request.getParameter(id)));
			}
			//先去查询是否有记录
			ProjectClaimRecordEntity info = claimService.recordInfo(user.getId());
			if (info != null) {
				recordList.add(user);
			} else
				recordList1.add(user);

		}
		//1:先查询数据库是否有数据
		// 2：如果有先更新
		//3：没有插入
		ProjectClaimEntity projectClaimEntity = claimService.getByIds(claimId);//获取认领管理信息
		System.out.println(sum);
		projectClaimEntity.setClaimAmount(sum);//已领金额
		projectClaimEntity.setUnclaimedAmount(arrivalAmount.subtract(sum));//未领金额
		boolean claimEntity = claimService.updateByIds(projectClaimEntity);
		ValidatorUtil.validateEntity(claimEntity);
//		if(claimEntity==false){
//			return this.error("修改失败!");
//		}
		if (recordList != null && !recordList.isEmpty()) {
			boolean record = claimService.updateRecord(recordList);
			System.out.println(claimEntity);
			if (record != true) {
				return this.error("修改失败!");
			} else if (recordList1 != null && !recordList1.isEmpty()) {
				System.out.println("44444444444");
				return claimService.saveRecord(recordList1) ? success() : error("修改失败!");
			} else {
				System.out.println("55555555555");
				return this.success();
			}
		} else {
			return claimService.saveRecord(recordList1) ? success() : error("修改失败!");
		}
	}
}
